﻿using AutoMapper;
using MediatR;
using Traceability.Doamin;
using Traceability.ErrorCode;
using Traceability.Infratruvture.Interfares;
using Traceability.Read.Api.Application.Command.CommodityCommand;
using Traceability.Read.Api.Dto;

namespace Traceability.Read.Api.Application.CommandHander.CommodityHander
{
    public class GetCommodityIdHander : IRequestHandler<GetCommodityIdCommand, ApiResult<List<CommodityDto>>>
    {

        private readonly IMapper mapper;
        private readonly IBaseRequsitory<Commodity> baseRequsitory;
        private readonly IBaseRequsitory<CommodityName> baseRequsitory1;

        public GetCommodityIdHander(IMapper mapper, IBaseRequsitory<Commodity> baseRequsitory, IBaseRequsitory<CommodityName> baseRequsitory1)
        {
            this.mapper = mapper;
            this.baseRequsitory = baseRequsitory;
            this.baseRequsitory1 = baseRequsitory1;
        }

        /// <summary>
        /// id查询商品操作
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task<ApiResult<List<CommodityDto>>> Handle(GetCommodityIdCommand request, CancellationToken cancellationToken)
        {
            ApiResult<List<CommodityDto>> result = new ApiResult<List<CommodityDto>>();
            result.Code = ApiEnum.显示成功;
            result.Msg = ApiEnum.显示成功.ToString();

            var linq = from a in baseRequsitory.GetAll()
                       join b in baseRequsitory1.GetAll() on a.CommodityNameId equals b.CommodityNameId
                       select new CommodityDto
                       {
                           CommodityId = a.CommodityId,
                           CommodityNameId = a.CommodityNameId,
                           Cover = a.Cover,
                           C_Times = a.Time,
                           Time = a.Time,
                           Permit = a.Permit,
                           Enterprise = a.Enterprise,
                           Degree = a.Degree,
                           CreateTime = a.CreateTime,
                           IsDelete = a.IsDelete,
                           ProductNameName = b.ProductNameName,
                           UpdateTime = a.UpdateTime,
                       };

            if (request.CommodityId!=null)
            {
                linq = linq.Where(x=>x.CommodityId==request.CommodityId);
            }

            result.Data = mapper.Map<List<CommodityDto>>(linq);

            return Task.FromResult(result);
        }
    }
}
